﻿using UnityEngine;

namespace Core
{
    public class UIWidgetAsync : Component, IGameObject, IActive, IAwake<GameObject>
    {
        public GameObject gameObject { get; private set; }
        public Transform transform { get; private set; }

        public bool Active { get; private set; }

        protected GameObject UIObj;
        protected bool isLoadComplete;

        protected string ResPath;

        public virtual void Awake(GameObject go)
        {
            gameObject = go;
            transform = go.transform;
        }

        public virtual void Init()
        {
            if (UIObj == null)
            {
                return;
            }
            if (gameObject.activeSelf)
            {
                Active = true;
                OnShow();
            }
            else
            {
                Active = false;
            }
        }

        public override void Dispose()
        {
            if (IsDisposed) return;

            SetActive(false);

            ResPath = string.Empty;

            G.Res.Recycle(UIObj);
            UIObj = null;

            G.Res.Recycle(gameObject);
            gameObject = null;
            transform = null;

            G.UI.DisposeUIField(this);

            base.Dispose();
        }

        public void Load()
        {
            if (isLoadComplete == false)
            {
                LoadAsync().Coroutine();
            }
            else
            {
                OnLoadComplete();
            }
        }

        private async ETVoid LoadAsync()
        {
            if (string.IsNullOrWhiteSpace(ResPath))
            {
                log.err($"Error! WidgetAsync.LoadAsync  ResPath is NUll");
                return;
            }

            var asset = await G.Res.LoadAsync(ResPath);
            isLoadComplete = true;
            UIObj = UnityEngine.Object.Instantiate(asset.Obj, transform) as GameObject;

            UIObj.SetLayer(gameObject.layer);

            G.UI.ParseUIField(this, UIObj);

            OnLoadComplete();

            Init();
        }

        protected virtual void OnLoadComplete() { }

        public virtual void SetActive(bool active)
        {
            if (UIObj == null || Active == active)
            {
                return;
            }
            Active = active;
            Utils.Trans.SetActive(gameObject, active);
            if (active)
            {
                OnShow();
            }
            else
            {
                OnHide();
            }
        }

        protected virtual void OnShow() { }
        protected virtual void OnHide() { }

    }
}
